package com.hspedu.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hspedu.seckill.entity.Order;
import com.hspedu.seckill.entity.SeckillGoods;
import com.hspedu.seckill.entity.SeckillOrder;
import com.hspedu.seckill.entity.User;
import com.hspedu.seckill.exception.GlobalException;
import com.hspedu.seckill.mapper.OrderMapper;
import com.hspedu.seckill.model.constant.RespBeanEnum;
import com.hspedu.seckill.model.vo.GoodsVo;
import com.hspedu.seckill.service.OrderService;
import com.hspedu.seckill.service.SeckillGoodsService;
import com.hspedu.seckill.service.SeckillOrderService;
import com.hspedu.seckill.utils.MD5Util;
import com.hspedu.seckill.utils.UUIDUtil;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author: xujiabing
 * @date: 2024-10-05 16:39
 * @description 订单逻辑实现
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private SeckillOrderService seckillOrderService;

    @Autowired
    private OrderMapper orderMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 秒杀路径校验key前缀
     */
    private static final String CACHE_KEY_PREFIX = "seckillPath:";

    /**
     * 秒杀验证码缓存key前缀
     */
    private static final String CAPTCHA_CACHE_KEY_PREFIX = "captcha:";

    /**
     * 完成秒杀逻辑
     *
     * @param user
     * @param goodsVo
     * @return
     */
    @Override
    @Transactional
    public Order seckill(User user, GoodsVo goodsVo) {
        //fixme 2025-01-05 增加查询用户是否已经购买
        SeckillOrder selectSeckillOrder = seckillOrderService.getOne(
                new LambdaQueryWrapper<SeckillOrder>()
                        .eq(SeckillOrder::getUserId, user.getId())
                        .eq(SeckillOrder::getGoodsId, goodsVo.getId()));
        if (!Objects.isNull(selectSeckillOrder)) {
            throw new RuntimeException("用户已经秒杀过该商品");
        }

        //查询商品库存，并减少对应库存
        SeckillGoods seckillGoods = seckillGoodsService
                .getOne(new QueryWrapper<SeckillGoods>()
                        .eq("goods_id", goodsVo.getId()));

        //v1.0 完成一个基本的秒杀操作[这块不具备原子性],后面高并发情况下还会进行优化
        //seckillGoods.setStockCount(seckillGoods.getStockCount() - 1);
        //seckillGoodsService.updateById(seckillGoods);

        //1.mysql默认的事务隔离级别REPEATABLE READ 中，
        //2.执行UPDATE 语句时，会在事务中锁定要更新的行，
        //3.这可以防止其他会话在同一行上执行UPDATE 或DELETE 操作
        //v2.0
        boolean update = seckillGoodsService.update(
                new UpdateWrapper<SeckillGoods>()
                        .setSql("stock_count = stock_count - 1")
                        .eq("goods_id", goodsVo.getId())
                        .gt("stock_count", 0));
        if (!update) {//更新失败，说明没有库存
            // 将秒杀记录失败存入redis
            redisTemplate.opsForValue()
                    .set("seckillFail:" + user.getId() + ":" + goodsVo.getId(), -1);
            return null;
        }


        //生成普通订单信息
        Order order = new Order();
        order.setUserId(user.getId());
        order.setGoodsId(goodsVo.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsName(goodsVo.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(seckillGoods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);//未支付状态
        order.setCreateDate(new Date());
        orderMapper.insert(order);

        //生成秒杀订单信息
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setGoodsId(goodsVo.getId());
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setUserId(user.getId());
        seckillOrderService.save(seckillOrder);

        //将生成的秒杀订单,存入redis, 这样在查询某个用户是否已经秒杀过该商品就不用到数据库去查询
        //而是直接从redis 去查询，起到优化的作用
        //key设计: order:用户id:商品id
        ValueOperations opsForValue = redisTemplate.opsForValue();
        opsForValue.set("order:" + user.getId() + ":" + goodsVo.getId(), seckillOrder);

        return order;
    }

    /**
     * @description: 生成下单校验uuid
     * @author: xujiabing
     * @date: 2025-01-27 17:20
     * @param: user
     * @param: goodsVo
     * @return: String
     */
    @Override
    public String genOnOrderUUID(User user, Long goodsId) {

        if (Objects.isNull(user) || Objects.isNull(goodsId)) {
            throw new GlobalException(RespBeanEnum.REQUEST_ILLEGAL);
        }
        // 生成校验uuid, 并将uuid 存入redis
        String uuid = MD5Util.md5(UUIDUtil.uuid() + "123456");
        String cacheKey = getCacheKey(user.getId().toString(), goodsId.toString());
        // 设置过期时间为60秒
        redisTemplate.opsForValue().set(cacheKey, uuid, 60, TimeUnit.SECONDS);
        return uuid;

    }

    /**
     * @description: 校验下单uuid
     * @author: xujiabing
     * @date: 2025-01-27 17:20
     * @param: user
     * @param: goodsVo
     * @param: uuid
     * @return: Boolean
     */
    @Override
    public Boolean checkOnOrderUUID(User user, Long goodsId, String uuid) {

        if (Objects.isNull(user)
                || Objects.isNull(goodsId)
                || StringUtils.isEmpty(uuid)) {
            return false;
        }

        // 从缓存中获取生成的uuid
        String cacheKey = getCacheKey(user.getId().toString(), goodsId.toString());
        String cachedUUID = (String) redisTemplate.opsForValue().get(cacheKey);

        // 校验传入的uuid是否与缓存中的uuid一致
        return uuid.equals(cachedUUID);
    }

    /**
     * 校验秒杀验证码
     *
     * @param userId       用户ID
     * @param goodsId      商品ID
     * @param captchaValue 用户输入的验证码值
     * @return 布尔值，表示验证码是否正确
     */
    @Override
    public boolean checkCaptcha(String userId, String goodsId, String captchaValue) {
        // 必要的参数校验
        if (StringUtils.isEmpty(userId)
                || StringUtils.isEmpty(goodsId)
                || StringUtils.isEmpty(captchaValue)) {
            return false;
        }
        // 获取缓存key
        String cacheKey = genCaptchaCacheKey(userId, goodsId);
        // 从缓存中获取验证码
        String cachedCaptcha = (String) redisTemplate.opsForValue().get(cacheKey);
        // 校验验证码是否正确(忽略大小写)
        return captchaValue.equalsIgnoreCase(cachedCaptcha);

    }

    /**
     * 工具方法-获取秒杀验证码缓存key
     *
     * @param userId
     * @param goodsId
     * @return
     */
    @Override
    public String genCaptchaCacheKey(String userId, String goodsId) {
        return CAPTCHA_CACHE_KEY_PREFIX + userId + goodsId;
    }

    /**
     * 工具方法-获取 校验下单uuid 对应key
     *
     * @return
     */
    private String getCacheKey(String userId, String goodsId) {
        return CACHE_KEY_PREFIX + userId + goodsId;
    }
}
